#include <iostream>
#include <cstring>
#include <cstdio>
#include <cassert>
#include <fcntl.h>
#include <unistd.h>

using namespace std;

void test1()
{
    string file_name = "bite";
    string content = "linux so easy!";

    // 1. 打开 / 创建文件
    FILE* file = fopen(file_name.c_str(), "w+");
    // 判空
    if (file == NULL) {
        cout << "open file failed!" << endl;
        exit(-1);
    }

    // 2. 向文件写入内容
    size_t len = fwrite(content.c_str(), sizeof(char), content.size(), file);
    assert(len == content.size());

    // 3. 移动文件指针
    fseek(file, 0, SEEK_SET);

    // 4. 读取文件内容
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    size_t ret = fread(buf, sizeof(char), sizeof(buf), file);
    assert(ret > 0);
    cout << "读取内容成功: " << buf << endl;

    // 关闭
    fclose(file);
}

void test2()
{
    const char* file_name = "bite";
    const char* content = "i like linux!";

    // 1. 打开文件
    int fd = open(file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    assert(fd != -1);
    // 2. 写入内容
    ssize_t swtite = write(fd, content, strlen(content));
    assert(swtite == static_cast<ssize_t>(strlen(content)));
    // 3. 移动文件指针
    lseek(fd, 0, SEEK_SET);
    // 4. 读取文件内容
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    int len = read(fd, buffer, sizeof buffer);
    assert(len > 0);
    cout << "读取内容成功: " << buffer << endl;
    // 5. 关闭文件
    close(fd);
}

int main() {
    // test1();
    test2();

    return 0;
}